import GROUP_DATA from '../../utils/groups.js'

Page({
  data: {
    questions: [],
    currentQuestion: 0,
    isRecording: false,
    showResult: false,
    recognizedText: '',
    isCorrect: false,
    score: 0,
    recorderManager: null
  },

  onLoad(options) {
    const groupId = options.groupId;
    const groupData = GROUP_DATA.find(item => item.group.group_id === groupId);
    
    if (groupData) {
      // 生成测试题目
      const questions = this.generateQuestions(groupData.words);
      this.setData({ questions });
    }

    // 初始化录音管理器
    this.recorderManager = wx.getRecorderManager();
    this.initRecorderManager();
  },

  generateQuestions(words) {
    // 复制并打乱单词数组
    return [...words]
      .sort(() => Math.random() - 0.5)
      .map(word => ({
        word: word.word_english,
        image: word.word_image,
        chinese: word.word_chinese
      }));
  },

  initRecorderManager() {
    this.recorderManager.onStart(() => {
      this.setData({ isRecording: true });
    });

    this.recorderManager.onStop((res) => {
      this.setData({ isRecording: false });
      this.processRecognitionResult(res.tempFilePath);
    });

    this.recorderManager.onError((res) => {
      wx.showToast({
        title: '录音失败',
        icon: 'error'
      });
      this.setData({ isRecording: false });
    });
  },

  toggleRecording() {
    if (this.data.showResult) return;

    if (this.data.isRecording) {
      this.recorderManager.stop();
    } else {
      // 检查录音权限
      wx.authorize({
        scope: 'scope.record',
        success: () => {
          this.startRecording();
        },
        fail: () => {
          wx.showModal({
            title: '需要录音权限',
            content: '口语测试需要使用麦克风，是否前往设置开启权限？',
            success: (res) => {
              if (res.confirm) {
                wx.openSetting();
              }
            }
          });
        }
      });
    }
  },

  startRecording() {
    this.recorderManager.start({
      duration: 10000,
      sampleRate: 16000,
      numberOfChannels: 1,
      encodeBitRate: 48000,
      format: 'mp3'
    });
  },

  processRecognitionResult(audioFile) {
    // 这里应该调用实际的语音识别API
    // 目前使用模拟数据
    const currentWord = this.data.questions[this.data.currentQuestion].word;
    const recognized = Math.random() > 0.5 ? currentWord : 'wrong word';
    const isCorrect = recognized.toLowerCase() === currentWord.toLowerCase();

    this.setData({
      showResult: true,
      recognizedText: recognized,
      isCorrect: isCorrect,
      score: this.data.score + (isCorrect ? 1 : 0)
    });
  },

  nextQuestion() {
    if (!this.data.showResult) return;

    if (this.data.currentQuestion === this.data.questions.length - 1) {
      wx.navigateTo({
        url: `/pages/testResult/testResult?score=${this.data.score}&total=${this.data.questions.length}`
      });
      return;
    }

    this.setData({
      currentQuestion: this.data.currentQuestion + 1,
      showResult: false,
      recognizedText: '',
      isCorrect: false
    });
  }
}); 